import moment from "moment"

//根据提供的key值，提取数据
export function colunmData<T>(columns: Record<string, T>[], key: string): T[] {
    return columns.map(col => col[key])
}

//96点时间数据生成
export const dateRange96 = function () {
    const temp: string[] = [];
    const hours = new Array(24).fill(0);
    const moments = ["00", "15", "30", "45"];
    hours.forEach((item, index) => {
        if (`${index}`.length == 1) {
            hours[index] = `0${index}`;
        } else {
            hours[index] = `${index}`;
        }

        moments.forEach((item) => {
            temp.push(`${hours[index]}:${item}`);
        });
    });
    return temp;
};

//保留两位小数 rate为系数
export function toFixed2(num = 0, rate = 1) {
    return (num * rate).toFixed(2)
}

//开始时间不能超过结束时间
export function compareStartDateTime(start: string, end: string) {
    return moment(start).isBefore(end)
}

//给对象循环赋值,不存在不赋值，和Object.assign有区别
export function singleObjectAssign<T>(target: T, source: T): T {
    if (!source) return target
    for (const t in target) {
        target[t] = source[t]
    }
    return target
}

export function getUserIP() {
    return (window as any).returnCitySN["cip"] || '127.0.0.1'
}

//字符串是否可转化为JSON
export function isJSON(str: string) {
    if (typeof str == 'string') {
        try {
            const obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            console.log('error：' + str + '!!!' + e);
            return false;
        }
    }
}


/**
 * blob转化为json，常用于后端文件报错时处理
 * @param b Blob格式文件
 * @param callback 处理完返回的JSON文本
*/
export function blob2Json(b: Blob, callback: (c: unknown) => void) {
    const reader = new FileReader();
    reader.onload = function () {
        const content = reader.result as string;//内容就在这里
        if (isJSON(content)) {
            callback(JSON.parse(content))
        }
    };
    reader.readAsText(b);
}

export function uploadFile(accept: string, multiple = false) {
    const i = document.createElement('input')
    i.type = 'file'
    i.accept = accept
    i.multiple = multiple
    i.click()
    i.onchange = (e) => {
        console.log(e.target)
    }
    return i.value
}